package com.study.microservice.springcloud.service;

import com.study.microservice.springcloud.pojo.User;
import feign.hystrix.FallbackFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Author : 周世雄 <br>
 * Date : 2018/11/9 11:46 <br>
 * E-mail : zhoushixiong@chinasoftinc.com
 * Description :
 */
@FeignClient(name = "microservice-provider-user",fallbackFactory = FeignClientFallbackFactory.class)
public interface UserFeignClient {

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    User findById(@PathVariable("id") Long id);


    @Component
    class FeignClientFallbackFactory implements FallbackFactory<UserFeignClient> {

        private static final Logger LOGGER = LoggerFactory.getLogger(com.study.microservice.springcloud.service.FeignClientFallbackFactory.class);

        /**
         * 在项目启动的时候就会执行该方法<br>
         * * 这里使用了lambda表达式，所以jdk版本需要在1.8及以上
         * @param cause
         * @return
         */
        @Override
        public UserFeignClient create(Throwable cause) {
            // 日志最好放在给个fallback中，而不要放在create方法中。否则会在启动的时候就打印该日志
            return id -> {
                LOGGER.error("fallback; reason was:",cause);
                User user = new User();
                user.setId(-1L);
                user.setUsername("默认用户");
                return user;
            };
        }
    }
}
